package utils

import (
	"cron_table_admin/global"
	"cron_table_admin/internal/response"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
)

type ginFunc func(c *gin.Context) error

// HandleError 全局错误处理
func HandleError(GinFuncErr ginFunc) gin.HandlerFunc {
	return func(ctx *gin.Context) {
		r := ctx.Request
		mapResult := global.GetParameters(ctx)
		defer func() {
			if err := recover(); err != nil {
				//收集处理函数出现的未知panic
				global.LOGGER.Error("处理未知系统错误日志", zap.Any("Server system error: ", err), zap.String("ip", ctx.ClientIP()), zap.Any("method", r.Method), zap.Any("request path", r.URL.Path), zap.Any("resParameters:", mapResult))
				response.FailWithMessage("system error", ctx)
				ctx.Abort()
			}
		}()
		err := GinFuncErr(ctx)
		ctx.Next()
		if err != nil {
			global.LOGGER.Error("处理正常已知错误日志", zap.Any("request error ", err), zap.String("ip", ctx.ClientIP()), zap.Any("method", r.Method), zap.Any("request path", r.URL.Path), zap.Any("resParameters:", mapResult))
		}
	}
}
